<template>
	<view class="container" :style="appThemeStyle">
		<!-- 标题 -->
		<view class="page-title">个人信息</view>
		<!-- 表单组件 -->
		<view class="form-wrapper">
			<u-form :model="form" ref="uForm" label-width="140rpx">
				<u-form-item v-if="this.isOwer" label="头像">
					<button class="btn-normal" open-type="chooseAvatar" @click="onClickAvatar()"
						@chooseavatar="onChooseAvatar">
						<avatar-image v-if="avatarUrl" :url="avatarUrl" :width="100" />
						<text v-else style="color: #c0c4cc;">请选择头像</text>
					</button>
				</u-form-item>
				<u-form-item v-if="this.isOwer" label="昵称" prop="nickName">
					<u-input v-model="form.nickName" type="nickname" maxlength="30" placeholder="请输入昵称"
						@input="onInputNickName" @blur="onInputNickName" />
				</u-form-item>
				<u-form-item label="性别" prop="gender">
					<u-input v-model="form.gender" type="select" @click="isGenderShow = true" placeholder="请选择性别" />
					<u-action-sheet :list="genderSheetList" v-model="isGenderShow"
						@click="onGenderChange"></u-action-sheet>
				</u-form-item>
				<u-form-item label="出生日期" prop="birth">
					<u-input v-model="form.birth" type="select" @click="isBirthShow = true" placeholder="请选择出生日期" />
					<u-picker mode="time" start-year="1900" v-model="isBirthShow" :params="params"
						:default-time="defaultBirth" @confirm="onBirthChange"></u-picker>
				</u-form-item>
				<u-form-item label="体重(KG)" prop="weight">
					<u-input v-model="form.weight" type="number" placeholder="请输入体重" />
				</u-form-item>
				<u-form-item label="身高(CM)" prop="height">
					<u-input v-model="form.height" type="number" placeholder="请输入身高" />
				</u-form-item>
				<u-form-item label="病史" style="position: relative;">
					<u-input v-model="getMedHistory" placeholder="请输入病史" />
					<view
						style="width: 490rpx; height: 110rpx; position: absolute; right: 0; top: 0;z-index: 2; display: flex; align-items: center; justify-content: flex-end;"
						@click="onMedHistory">
						<u-icon name="arrow-down-fill" color="#c0c4cc"></u-icon>
					</view>
				</u-form-item>
			</u-form>
		</view>
		<!-- 操作按钮 -->
		<view class="footer">
			<view class="btn-wrapper">
				<button v-if="!mobile && isOwer" class="btn-item btn-item-main" :class="{ disabled }"
					open-type="getPhoneNumber" @getphonenumber="handelMpWeixinMobileLogin($event)">保存</button>
				<button v-else class="btn-item btn-item-main" :class="{ disabled }"
					@click="handleSubmit(false)">保存</button>
			</view>
		</view>

		<u-toast ref="uToast1" />
		<SelectPopup :show="isMedHistoryShow" :value="form.medicalHistory" :list="allMedHistoryList"
			@updateShow="e => isMedHistoryShow = e" @change="onSelectChange" />
	</view>
</template>

<script>
	import store from '@/store';
	import AvatarImage from '@/components/avatar-image';
	import SelectPopup from '@/components/reservation-popup/select-popup.vue';
	import * as UserApi from '@/api/user';
	import * as HomeApi from '@/api/home/index.js';
	import * as UploadApi from '@/api/upload';
	import WXUtils from "@/utils/WXUtils.js";
	import StorageUtils from "@/utils/StorageUtils";
	import CacheConfig from '@/config/CacheConfig';

	export default {
		components: {
			AvatarImage,
			SelectPopup
		},
		data() {
			return {
				// 是否是当前用户
				isOwer: true,
				// 按钮禁用
				disabled: false,
				// 头像路径 (用于显示)
				avatarUrl: '',
				// 临时图片 (用于上传)
				tempFile: null,
				// 手机号
				mobile: '',
				// 用户id
				userId: '',
				// 病史
				medHistoryList: [],
				// 所有病史
				allMedHistoryList: [],
				// 表单数据
				form: {
					avatarUrl: '',
					nickName: '',
					gender: '',
					birth: '',
					weight: '',
					height: '',
					medicalHistory: '',
					code: '',
					loginCode: '',
					encryptedData: '',
					iv: '',
				},
				// 验证规则
				rules: {
					nickName: [{
						required: true,
						message: '请输入用户昵称',
						trigger: ['blur', 'change']
					}],
					gender: [{
						required: true,
						message: '请选择用户性别',
						trigger: ['blur', 'change']
					}],
					birth: [{
						required: true,
						message: '请选择用户出生日期',
						trigger: ['blur', 'change']
					}],
					weight: [{
						required: true,
						type: "number",
						message: '请输入用户体重',
						trigger: ['blur', 'change']
					}],
					height: [{
						required: true,
						type: "number",
						message: '请输入用户身高',
						trigger: ['blur', 'change']
					}]
				},
				// 性别列表显示
				isGenderShow: false,
				// 性别列表
				genderList: [{
						label: '男',
						value: 1,
					},
					{
						label: '女',
						value: 2,
					}
				],
				// 日期选择显示
				isBirthShow: false,
				params: {
					year: true,
					month: true,
					day: true,
				},
				defaultBirth: "2000-01-01",
				isMedHistoryShow: false,
			}
		},
		computed: {
			genderSheetList() {
				const list = [];
				this.genderList.forEach(v => {
					list.push({
						text: v.label
					})
				})
				return list;
			},
			getMedHistory() {
				const arr = this.medHistoryList.map(v => v.medicalName);
				return arr.join(",");
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			console.log("options", options);
			if (options.userId) {
				console.log("获取被邀请用户信息");
				this.isOwer = false;
				this.userId = options.userId;
				this.form.nickName = options.nickName;
			} else {
				console.log("获取当前登录用户信息");
				this.isOwer = true;
				// 获取当前用户信息
				this.getUserInfo();
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			// 获取当前用户信息
			getUserInfo() {
				const app = this;
				UserApi.info()
					.then(result => {
						console.log("result", result);
						const userInfo = result.obj;
						// app.avatarUrl = userInfo.avatar_url
						// app.form.avatarId = userInfo.avatar_id
						if (userInfo.mobile) {
							if (userInfo.birth) {
								const birth = this.$u.timeFormat(Number(userInfo.birth), 'yyyy-mm-dd');
								this.form.birth = birth;
								this.defaultBirth = birth;
							}
							const gender = this.genderList.find(v => v.value == userInfo.gender) ? this.genderList
								.find(v => v.value == userInfo.gender).label : '';
							// console.log("gender", gender);
							// console.log("birth", birth);
							this.form.avatarUrl = userInfo.avatarUrl;
							this.form.nickName = userInfo.nickName;
							this.form.weight = userInfo.weight * 1;
							this.form.height = userInfo.height * 1;
							this.form.medicalHistory = userInfo.medicalHistory;
							this.form.gender = gender;
							this.avatarUrl = userInfo.avatarUrl;
							this.mobile = userInfo.mobile;
							this.userId = userInfo.id;

							this.getUserMedHistory();
						}
					})
			},
			getUserMedHistory() {
				const arr = this.form.medicalHistory ? this.form.medicalHistory.split(",").map(v => Number(v)) : [];
				UserApi.getAllMedical().then(res => {
					if (res.obj) {
						this.allMedHistoryList = res.obj;
						this.medHistoryList = res.obj.filter(v => arr.includes(v.id));
					}
				})
			},
			// 点击头像按钮事件
			onClickAvatar() {
				// #ifdef MP-WEIXIN
				return
				// #endif
				this.chooseImage()
			},
			// 选择头像事件 - 仅限微信小程序
			onChooseAvatar({
				detail
			}) {
				// #ifdef MP-WEIXIN
				const app = this
				app.avatarUrl = detail.avatarUrl
				app.tempFile = {
					path: app.avatarUrl
				}
				// #endif
			},
			// 选择图片
			chooseImage() {
				const app = this
				// 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						app.tempFile = tempFiles[0]
						app.avatarUrl = app.tempFile.path
					}
				});
			},
			// 性别
			onGenderChange(e) {
				this.form.gender = this.genderSheetList[e].text;
			},
			// 出生日期
			onBirthChange(e) {
				// console.log("onBirthChange", e);
				const {
					year,
					month,
					day
				} = e;
				this.form.birth = `${year}-${month}-${day}`;
			},
			onMedHistory() {
				this.isMedHistoryShow = true;
			},
			onSelectChange(e) {
				this.medHistoryList = e;
				this.form.medicalHistory = (e.map(v => v.id)).join(",");
			},
			// 上传图片
			uploadFile() {
				const app = this
				return UploadApi.image([app.tempFile])
					.then(fileIds => {
						console.log("fileIds", fileIds);
						app.form.avatarUrl = "https://" + fileIds,
							app.tempFile = null
						return true
					})
					.catch(() => {
						return false
					})
			},
			async handelMpWeixinMobileLogin({
				detail
			}) {
				console.log("detail", detail);
				const app = this;
				app.$refs.uForm.validate(async valid => {
					if (!valid) return
					if (detail.errMsg != 'getPhoneNumber:ok') {
						console.log('微信授权获取手机号失败', detail);
						return;
					}
					if (detail.errMsg == 'getPhoneNumber:ok') {
						this.form.code = detail.code;
						// this.form.loginCode = detail.code;
						this.form.encryptedData = detail.encryptedData;
						this.form.iv = detail.iv;
						const {
							code
						} = await WXUtils.login();
						console.log("code", code);
						this.form.loginCode = code;
						this.handleSubmit();
					}
				})
			},
			// 确认修改
			async handleSubmit(isNew = true) {
				const app = this;
				// 判断是否重复提交
				if (app.disabled === true) return;
				app.$refs.uForm.validate(async valid => {
					if (!valid) return
					// 按钮禁用
					app.disabled = true
					// 先上传头像图片
					if (app.tempFile && !await app.uploadFile()) {
						app.$toast('很抱歉，头像上传失败')
						app.disabled = false
						return

					}
					// 提交保存个人信息
					console.log("app.form", app.form);
					const genderObj = this.genderList.find(v => v.label === app.form.gender);
					const birthTimeStamp = new Date(app.form.birth).getTime();
					if (isNew) {
						const param = {
							...app.form,
							gender: genderObj.value,
							birth: birthTimeStamp,
							appid: "wx9defdd2125f88fbb"
						};
						console.log("updateUserInfo param", param);
						UserApi.updateUserInfo(param).then(res => {
							console.log("updateUserInfo error", res);
							app.$toast("修改成功");
							app.disabled = false;
							StorageUtils.save('USER_INFO_KEY', res.obj);
							uni.navigateBack();
						}).catch(err => {
							console.log("updateUserInfo error", err);
						});
					} else {
						const param = {
							...this.form,
							id: this.userId,
							gender: genderObj.value,
							birth: birthTimeStamp,
							medicalHistory: this.form.medicalHistory || '',
						}
						delete param.iv;
						delete param.code;
						delete param.loginCode;
						delete param.encryptedData;

						if (!this.isOwer) {
							let avatarUrl = "";
							let type = "";
							let sex = app.form.gender == "男" ? 'man' : 'woman';
							const age = this.calculateAge(app.form.birth);
							if (age > 50) {
								type = "old";
							} else if (age > 20) {
								type = "middle";
							} else if (age > 10) {
								type = "young";
							} else if (age >= 0) {
								type = "child";
								sex = "";
							}
							avatarUrl = `${this.$IMAGE_BASE_URL}/static/ic_${type}_${sex}.png`;
							param.avatarUrl = avatarUrl;
						}

						console.log("updateUserInfoById param", param);
						UserApi.updateUserInfoById(param).then(res => {
							console.log("updateUserInfoById success", res);
							this.$toast("修改成功");
							if (this.isOwer) {
								UserApi.info().then(result => {
									console.log("UserApi.info result", result);
									const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
									console.log("StorageUtils userInfo", userInfo);
									if(userInfo) {
										console.log("修改用户信息");
										StorageUtils.save(CacheConfig.USER_INFO_KEY, result.obj);
										uni.navigateBack();
									} else {
										console.log("用户重新登录");
										uni.reLaunch({
											url:'/pages/oxygen/index'
										})
									}
								})
							} else {
								this.bindHome();
							}
						}).catch(err => {
							console.log("updateUserInfoById error", err);
						})
					}
				})
			},
			bindHome() {
				const homeId = StorageUtils.get("homeId");
				const param = {
					homeId,
					invitedUserId: this.userId,
				}
				console.log("joinHome param", param);
				HomeApi.joinHome(param).then(res => {
					uni.navigateBack({
						delta: 3
					});
				}).catch(err => {
					console.log("joinHome error", err);
				})
			},
			// 计算年龄
			calculateAge(birthDate) {
				const today = new Date();
				const birth = new Date(birthDate);
				let age = today.getFullYear() - birth.getFullYear();
				const monthDifference = today.getMonth() - birth.getMonth();
				if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birth.getDate())) {
					age--;
				}
				return age;
			},
			// 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
			onInputNickName(val) {
				if (val) {
					this.form.nickName = val;
				}
			},
		}
	}
</script>

<style>
	page {
		background: #f7f8fa;
	}
</style>
<style lang="scss" scoped>
	.container {}

	.page-title {
		width: 94%;
		margin: 0 auto;
		padding-top: 40rpx;
		font-size: 28rpx;
		color: rgba(69, 90, 100, 0.6);
	}

	.form-wrapper {
		margin: 20rpx auto 20rpx auto;
		padding: 0 40rpx;
		width: 94%;
		box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
		border-radius: 16rpx;
		background: #fff;
	}

	/* 底部操作栏 */

	.footer {
		margin-top: 80rpx;

		.btn-wrapper {
			height: 100%;
			// display: flex;
			// align-items: center;
			padding: 0 20rpx;
		}

		.btn-item {
			flex: 1;
			font-size: 28rpx;
			height: 86rpx;
			color: #fff;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.btn-item-wechat {
			background: #0ba90b;
			margin-bottom: 26rpx;
		}

		.btn-item-main {
			// background: linear-gradient(to right, $main-bg, $main-bg2);
			// color: $main-text;
			width: 367rpx;
			border-radius: 97rpx;
			background-color: #ff790f;
			font-family: SourceHanSansCN;
			// font-size: 36rpx;
			color: #FFFFFF;
			font-weight: bold;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 80rpx auto 0 auto;

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}

	}
</style>